package com.haoxuer.discover.weibo.data.dao.impl;

import com.haoxuer.discover.data.core.CriteriaDaoImpl;
import com.haoxuer.discover.data.enums.StoreState;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.weibo.data.dao.WeiBoDao;
import com.haoxuer.discover.weibo.data.dao.WeiBoLikeDao;
import com.haoxuer.discover.weibo.data.entity.WeiBo;
import com.haoxuer.discover.weibo.data.enums.LikeType;
import com.haoxuer.discover.weibo.data.enums.WeiBoType;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * Created by imake on 2019年01月02日09:59:44.
 */
@Repository

public class WeiBoDaoImpl extends CriteriaDaoImpl<WeiBo, Long> implements WeiBoDao {

  @Autowired
  private WeiBoLikeDao likeDao;

  @Override
  public WeiBo findById(Long id) {
    if (id == null) {
      return null;
    }
    return get(id);
  }

  @Override
  public WeiBo countLike(Long id) {
    if (id == null) {
      return null;
    }
    WeiBo weiBo = get(id);
    if (weiBo == null) {
      return null;
    }
    Long likes = likeDao.countQuery(Filter.eq("weiBo.id", id), Filter.eq("likeType", LikeType.like));
    if (likes == null) {
      likes = 0L;
    }
    weiBo.setLikes(likes);
    return weiBo;
  }

  @Override
  public WeiBo countComment(Long id) {
    if (id == null) {
      return null;
    }
    WeiBo weiBo = get(id);
    if (weiBo == null) {
      return null;
    }
    Long comments = countQuery(Filter.eq("root.id", id), Filter.eq("weiBoType", WeiBoType.reply));
    if (comments == null) {
      comments = 0L;
    }
    weiBo.setReplys(comments);
    return weiBo;
  }

  @Override
  public WeiBo save(WeiBo bean) {
    bean.setStoreState(StoreState.normal);
    getSession().save(bean);
    return bean;
  }

  @Override
  public WeiBo deleteById(Long id) {
    WeiBo entity = super.get(id);
    if (entity != null) {
      getSession().delete(entity);
    }
    return entity;
  }

  @Override
  protected Class<WeiBo> getEntityClass() {
    return WeiBo.class;
  }

  @Autowired
  public void setSuperSessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
}